<template>
  <div class="profit-statistics">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <div class="header-title">
            <i class="el-icon-trend-charts"></i>
            <span>股票收益分析</span>
            <small class="stock-name">{{ currentStockName }}</small>
          </div>
          <el-select
            v-model="selectedStock"
            placeholder="切换股票"
            style="width: 160px"
            @change="handleStockChange"
            filterable
            size="small"
          >
            <el-option
              v-for="stock in stockList"
              :key="stock.stockCode"
              :label="`${stock.stockName}`"
              :value="stock.stockCode"
            />
          </el-select>
        </div>
      </template>

      <div v-if="loading" class="loading">
        <el-skeleton :rows="2" animated />
      </div>

      <div v-else-if="profitData" class="statistics-content">
        <!-- 核心收益数据 -->
        <div class="core-metrics">
          <el-row :gutter="15">
            <el-col :span="8">
              <div class="metric-card">
                <div class="metric-title">做T收益</div>
                <div class="metric-value" :class="getProfitClass(allTProfit)">
                  ¥{{ formatNumber(allTProfit) }}
                </div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="metric-card">
                <div class="metric-title">总盈亏</div>
                <div class="metric-value" :class="getProfitClass(profitData.profitLoss)">
                  ¥{{ formatNumber(profitData.profitLoss) }}
                </div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="metric-card">
                <div class="metric-title">涨跌幅</div>
                <div class="metric-value" :class="getProfitClass(priceIncrease)">
                  {{ formatNumber(priceIncrease) }}%
                </div>
              </div>
            </el-col>
          </el-row>
        </div>

        <el-divider class="section-divider" />

        <!-- 收益占比分析 -->
        <div class="profit-analysis">
          <div class="analysis-grid">
            <div class="analysis-item">
              <el-progress
                type="circle"
                :percentage="Math.abs(tProfitPercentage)"
                :color="getProgressColor(tProfitPercentage)"
                :width="120"
                :stroke-width="8"
              >
                <template #default="{ percentage }">
                  <div class="progress-detail">
                    <div class="progress-value">{{ percentage }}%</div>
                    <div class="progress-label">T收益占比</div>
                  </div>
                </template>
              </el-progress>
            </div>
            
            <div class="analysis-item">
              <el-progress
                type="circle"
                :percentage="Math.abs(totalProfitPercentage)"
                :color="getProgressColor(totalProfitPercentage)"
                :width="120"
                :stroke-width="8"
              >
                <template #default="{ percentage }">
                  <div class="progress-detail">
                            <div class="progress-value">{{ Number(percentage).toFixed(2) }}%</div>
                    <div class="progress-label">投资占比</div>
                  </div>
                </template>
              </el-progress>
            </div>
          </div>
        </div>

        <el-divider class="section-divider" />

        <!-- 价格分析 -->
        <div class="price-analysis">
          <div class="price-grid">
            <div class="price-item">
              <div class="price-label">当前价</div>
              <div class="price-value">¥{{ formatNumber(profitData.currentPrice) }}</div>
            </div>
            <div class="price-item">
              <div class="price-label">保本价</div>
              <div class="price-value">¥{{ formatNumber(profitData.breakEvenPrice) }}</div>
            </div>
            <div class="price-item">
              <div class="price-label">差点</div>
              <div class="price-value">{{ pointDifference }}</div>
            </div>
            <div class="price-item">
              <div class="price-label">做T后差点</div>
              <div class="price-value">{{ tPointDifference }}</div>
            </div>
          </div>
          
          <div class="price-bar">
            <div class="price-bar-label">相对保本价位置</div>
            <el-progress
              :percentage="Math.abs(relativePosition)"
              :color="getProgressColor(relativePosition)"
              :format="() => `${relativePosition > 0 ? '+' : ''}${formatNumber(relativePosition)}%`"
              :stroke-width="6"
            />
          </div>
        </div>
      </div>

      <div v-else class="empty">
        <el-empty 
          description="请选择股票查看收益统计" 
          :image-size="80"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import { getStockList } from '@/api/stockTrading'
import { getStockLatestData } from '@/api/stockStatistics'
import { getTotalTProfitByStockCode } from '@/api/stockTTransaction';
export default {
  name: 'ProfitStatistics',
  props: {
    stockCode: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      selectedStock: '',
      stockList: [],
      profitData: null,
      loading: false,
      allTProfit: 0
    }
  },
  computed: {
    currentStockName() {
      if (!this.stockCode || !this.stockList.length) return '';
      const stock = this.stockList.find(s => s.stockCode === this.stockCode);
      return stock ? stock.stockName : '';
    },
    
    tProfitPercentage() {
      if (!this.allTProfit || this.profitData?.profitLoss === 0) return 0
      return parseFloat((Math.abs(this.allTProfit) / Math.abs(this.profitData.profitLoss)) * 100).toFixed(1)
    },
    
    totalProfitPercentage() {
      return Math.max(0, 100 - Math.abs(this.tProfitPercentage))
    },
    
    pointDifference() {
      if (!this.profitData) return 0
      let diff = (this.profitData.currentPrice - this.profitData.breakEvenPrice) * 1000
      if(this.allTProfit > 0) {
        diff = diff - (this.allTProfit / this.profitData.totalShares) * 1000;
      }
      return Math.round(diff * 100) / 100
    },
    tPointDifference(){
      console.log(this.profitData);
      if (!this.profitData) return 0
      const diff = (this.profitData.currentPrice - this.profitData.breakEvenPrice) * 1000
      return Math.round(diff * 100) / 100
    },
    priceIncrease() {
      if (!this.profitData || this.profitData.breakEvenPrice === 0) return 0
      return ((this.profitData.currentPrice - this.profitData.breakEvenPrice) / this.profitData.breakEvenPrice) * 100
    },
    
    relativePosition() {
      return this.priceIncrease
    }
  },
  async mounted() {
    await this.loadStockList()
    this.selectedStock = this.stockCode
  },
  watch: {
    stockCode: {
      handler(newCode) {
        if (newCode && newCode.trim()) {
          this.selectedStock = newCode
          this.handleStockChange(newCode)
        }
      },
      immediate: true
    }
  },
  methods: {
    async loadStockList() {
      try {
        const response = await getStockList()
        if (response.code === 200) {
          this.stockList = response.data || []
        }
      } catch (error) {
        this.$message.error('加载股票列表失败')
      }
    },
    async handleStockChange(stockCode) {
      if (!stockCode) {
        this.profitData = null
        return
      }
      
      getTotalTProfitByStockCode(stockCode).then(response => {
        this.allTProfit = response.data || 0
      })
      
      this.loading = true
      try {
        const response = await getStockLatestData(stockCode)
        if (response.code === 200 && response.data) {
          this.profitData = response.data
        }
      } catch (error) {
        this.$message.error('获取数据失败')
      } finally {
        this.loading = false
      }
    },
    formatNumber(value) {
      if (value === null || value === undefined) return '0.00'
      return parseFloat(value).toFixed(3)
    },
    getProfitClass(value) {
      if (value > 0) return 'profit-positive'
      if (value < 0) return 'profit-negative'
      return 'profit-zero'
    },
    getProgressColor(value) {
      if (value > 0) return '#67C23A'
      if (value < 0) return '#F56C6C'
      return '#909399'
    }
  }
}
</script>

<style scoped>
.profit-statistics {
  padding: 10px;
  max-width: 600px;
  margin: 0 auto;
}

.box-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.header-title i {
  color: #409EFF;
}

.stock-name {
  font-size: 12px;
  color: #909399;
  font-weight: normal;
}

.core-metrics {
  margin-bottom: 15px;
}

.metric-card {
  text-align: center;
  padding: 12px 8px;
  background: #f8f9fa;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.metric-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.metric-title {
  font-size: 12px;
  color: #606266;
  margin-bottom: 6px;
  font-weight: 500;
}

.metric-value {
  font-size: 18px;
  font-weight: bold;
  line-height: 1.2;
}

.profit-positive {
  color: #F56C6C;
}

.profit-negative {
  color: #67C23A;
}

.profit-zero {
  color: #909399;
}

.section-divider {
  margin: 15px 0;
}

.analysis-grid {
  display: flex;
  justify-content: space-around;
  margin: 10px 0;
}

.analysis-item {
  text-align: center;
}

.progress-detail {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.progress-value {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.progress-label {
  font-size: 11px;
  color: #909399;
  margin-top: 2px;
}

.price-grid {
  display: flex;
  justify-content: space-around;
  margin: 10px 0;
}

.price-item {
  text-align: center;
  padding: 8px;
}

.price-label {
  font-size: 11px;
  color: #606266;
  margin-bottom: 4px;
}

.price-value {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.price-bar {
  margin: 10px 0;
}

.price-bar-label {
  font-size: 11px;
  color: #909399;
  margin-bottom: 6px;
  text-align: center;
}

.loading {
  padding: 30px 0;
  text-align: center;
}

.empty {
  padding: 30px 0;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .profit-statistics {
    padding: 5px;
  }
  
  .price-grid {
    flex-direction: column;
  }
  
  .price-item {
    margin-bottom: 10px;
  }
}
</style>